package com.leo.train.business.service.Impl;

import com.leo.train.business.dto.ConfirmOrderTicketDto;
import com.leo.train.business.entity.ConfirmOrder;
import com.leo.train.business.entity.DailySeat;
import com.leo.train.business.entity.DailyTrainTicket;
import com.leo.train.business.feign.MemberFeign;
import com.leo.train.business.mapper.ConfirmOrderMapper;
import com.leo.train.business.mapper.DailySeatMapper;
import com.leo.train.business.mapper.cust.DailyTrainTicketMapperCust;
import com.leo.train.business.service.AfterConfirmOrderService;
import com.leo.train.common.context.LoginMemberContext;
import com.leo.train.common.enums.ConfirmOrderStatusEnum;
import com.leo.train.common.req.MemberTicketReq;
import com.leo.train.common.resp.CommonResp;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AfterConfirmOrderServiceImpl implements AfterConfirmOrderService {
    @Autowired
    private DailySeatMapper dailySeatMapper;
    @Autowired
    private DailyTrainTicketMapperCust dailyTrainTicketMapperCust;
    @Resource
    private MemberFeign memberFeign;
    @Autowired
    private ConfirmOrderMapper confirmOrderMapper;
    // 5. 选中座位后，做事务处理
    // 5.1 座位表修改售卖情况sell字段
    // 5.2 余票详情表修改余票
    // 5.3 为会员增加购票记录（新增购票记录表）
    // 5.4 确认订单表修改状态为成功
    @Override
//    @GlobalTransactional
    public void afterDoConfirm(DailyTrainTicket dailyTrainTicket, List<DailySeat> finalSeatList, List<ConfirmOrderTicketDto> tickets, ConfirmOrder confirmOrder) {
//        log.info("Seata的全局事务ID：{}", RootContext.getXID());
        // 5.1 座位表修改售卖情况sell字段
        for (int j = 0; j < finalSeatList.size(); j++) {
            DailySeat dailySeat = finalSeatList.get(j);
            DailySeat seatForUpdate = new DailySeat() ;
            seatForUpdate.setId(dailySeat.getId());
            seatForUpdate.setSell(dailySeat.getSell());
            seatForUpdate.setUpdateTime(new Date());
            dailySeatMapper.update(seatForUpdate);

            // 5.2 余票详情表修改余票
            Integer startIndex = dailyTrainTicket.getStartIndex();
            Integer endIndex = dailyTrainTicket.getEndIndex();
            char[] chars = seatForUpdate.getSell().toCharArray();
            Integer maxStartIndex = endIndex - 1;
            Integer minEndIndex = startIndex + 1;
            Integer minStartIndex = 0;
            for (int i = startIndex - 1; i >= 0; i--) {
                char aChar = chars[i];
                if (aChar == '1') {
                    minStartIndex = i + 1;
                    break;
                }
            }
            log.info("影响出发站区间：" + minStartIndex + "-" + maxStartIndex);

            Integer maxEndIndex = seatForUpdate.getSell().length();
            for (int i = endIndex; i < seatForUpdate.getSell().length(); i++) {
                char aChar = chars[i];
                if (aChar == '1') {
                    maxEndIndex = i;
                    break;
                }
            }
            log.info("影响到达站区间：" + minEndIndex + "-" + maxEndIndex);

            dailyTrainTicketMapperCust.updateCountBySell(
                    dailySeat.getDate(),
                    dailySeat.getTrainCode(),
                    dailySeat.getSeatType(),
                    minStartIndex,
                    maxStartIndex,
                    minEndIndex,
                    maxEndIndex);

            // 调用会员服务接口，为会员增加一张车票
            MemberTicketReq memberTicketReq = new MemberTicketReq();
            memberTicketReq.setMemberId(confirmOrder.getMemberId());
            memberTicketReq.setPassengerId(tickets.get(j).getPassengerId());
            memberTicketReq.setPassengerName(tickets.get(j).getPassengerName());
            memberTicketReq.setTrainDate(dailyTrainTicket.getDate());
            memberTicketReq.setTrainCode(dailyTrainTicket.getTrainCode());
            memberTicketReq.setCarriageIndex(dailySeat.getCarriageIndex());
            memberTicketReq.setSeatRow(dailySeat.getRow());
            memberTicketReq.setSeatCol(dailySeat.getCol());
            memberTicketReq.setStartStation(dailyTrainTicket.getStart());
            memberTicketReq.setStartTime(dailyTrainTicket.getStartTime());
            memberTicketReq.setEndStation(dailyTrainTicket.getEnd());
            memberTicketReq.setEndTime(dailyTrainTicket.getEndTime());
            memberTicketReq.setSeatType(dailySeat.getSeatType());
            CommonResp<Object> commonResp = memberFeign.save(memberTicketReq);
            log.info("调用member接口，返回：{}", commonResp);

            // 5.4 确认订单表修改状态为成功
            ConfirmOrder confirmOrderForUpdate = new ConfirmOrder();
            confirmOrderForUpdate.setId(confirmOrder.getId());
            confirmOrderForUpdate.setUpdateTime(new Date());
            confirmOrderForUpdate.setStatus(ConfirmOrderStatusEnum.SUCCESS.getCode());
            confirmOrderMapper.update(confirmOrderForUpdate);

        }
    }
}
